package com.wbsxch.example.springsecurity.config.authentication;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.annotation.Resource;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)  //  启用方法级别的权限认证
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //@Resource
    //private MyAuthenticationProvider authenticationProvider;
    @Resource
    private MyAccessDeniedHandler accessDeniedHandler;
    @Resource
    private MyAuthenticationFailureHandler failureHandler;
    @Resource
    private MyAuthenticationSuccessHandler successHandler;

    @Resource
    private SecurityUserDetailsService userDetailsService;


    /*@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 加入自定义的安全认证
        auth.authenticationProvider(authenticationProvider);
    }*/

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                //.exceptionHandling().authenticationEntryPoint(new MyAuthenticationEntryPoint()).and()
                .authorizeRequests()
                //.httpBasic().authenticationEntryPoint(authenticationEntryPoint)
                //.and()
                .anyRequest()
                .authenticated()// 其他 url 需要身份认证
                .and()
                .formLogin()  //开启登录
                .usernameParameter("username")
                .passwordParameter("password")
                .loginProcessingUrl("/login")
                .successHandler(successHandler) // 登录成功
                .failureHandler(failureHandler) // 登录失败
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/logout")
                //.logoutSuccessHandler(logoutSuccessHandler)
                .permitAll();
                //.and()
                //.exceptionHandling().accessDeniedHandler(accessDeniedHandler);
    }

    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
